//
//  SoftwareDevelop.m
//  HappyStore
//
//  Created by 点点充 on 16/1/20.
//  Copyright © 2016年 LLJ. All rights reserved.
//

#import "SoftwareDevelop.h"
#import "SoftwareCell.h"
#import "serviceInfo.h"
#import "SoftEnterpriseCell.h"
@interface SoftwareDevelop ()
{
    NSMutableArray *_aryInfo;
    NSInteger paggge;
    
    NSMutableDictionary *muDicParameters;
    
    NSString *strProjectId;
}
@end

@implementation SoftwareDevelop


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"白色背景"] forBarMetrics:UIBarMetricsDefault];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
        [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 190, 44)];
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.font = [UIFont systemFontOfSize:19];
    titleLabel.text = _strType;
    titleLabel.textColor = RGB(45, 45, 45);
    titleLabel.textAlignment = NSTextAlignmentCenter;
    self.navigationItem.titleView = titleLabel;
    // 设置返回按钮
    UIBarButtonItem *leftItem = [UIBarButtonItem itemWithTarget:self action:@selector(leftBarButtonItemClick) image:@"返回" highImage:@"返回"]; 
    self.navigationItem.leftBarButtonItem = leftItem;
    
//    UIBarButtonItem *rightBar = [[UIBarButtonItem alloc] initWithTitle:@"筛选" style:UIBarButtonItemStylePlain target:self action:@selector(btnClickRight)];
//    self.navigationItem.rightBarButtonItem = rightBar;
    
    _aryInfo = [NSMutableArray array];
    paggge = 1;
    
    
    _mainTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        if (_aryInfo.count != 0) {
            if ([[USER_DEFAULTS objectForKey:@"isOpenSound"] boolValue]) {//声音开关
                NSString *path = [[NSBundle mainBundle]pathForResource:@"refresh"
                                                                ofType:@"wav"];
                SystemSoundID soundID;
                AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:path], &soundID);
                AudioServicesPlaySystemSound(soundID); //仅播放音频
            }
            paggge = 1;
            [muDicParameters setObject:@"1" forKey:@"page"];
            [self startSearch];
        }else {
            [_mainTableView.mj_header endRefreshing];
        }
    }];
    
    
    
    _mainTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        paggge += 1;
        [muDicParameters setObject:[NSString stringWithFormat:@"%ld",paggge] forKey:@"page"];
        [self startSearch];
    }];
    
    _mainTableView.mj_footer.hidden = YES;
    
    [[NSNotificationCenter defaultCenter]  addObserver:self
                                              selector:@selector(StartShaiXuanSearch:) name:@"StartShaiXuanSoftwareDevelop"
                                                object:nil];
    if (muDicParameters == nil) {
        muDicParameters = [NSMutableDictionary dictionary];
        [muDicParameters setObject:@"1" forKey:@"page"];
        [muDicParameters setObject:_strType forKey:@"categoryName"];
    }
    
    [self showRoundProgressWithTitle:@"请稍后..."];
    [self startSearch];
    
    self.mainSearchBar.layer.borderWidth = 1.f;
    self.mainSearchBar.layer.borderColor = [RGB(235, 235, 235) CGColor];
    
    //开启侧滑
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
    
}

- (void)leftBarButtonItemClick{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)StartShaiXuanSearch:(NSNotification *)dic
{
    muDicParameters = [NSMutableDictionary dictionaryWithDictionary:dic.userInfo];//通过这个获取到传递的对象
    _aryInfo = [NSMutableArray array];
    [self startSearch];
    
}

/**
 *  @author LLJ, 16-01-16 17:01:06
 *
 *  rightBarClick
 */
- (void)btnClickRight
{
    //取消显示后退键文字
    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleDone target:nil action:nil];
    self.navigationItem.backBarButtonItem = barButtonItem;
    
    [self performSegueWithIdentifier:@"pushSoftwareDevelopShaiXuan" sender:self];
    
}

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    if (_aryInfo.count != 0) {
        _aryInfo = [NSMutableArray array];
        [_mainTableView reloadData];
    }
    return YES;
}

- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar
{
    //NSLog(@"%@",searchBar.text);
    
    if (searchBar.text.length == 0) {
        return YES;
    }else {
        paggge = 1;
        muDicParameters = [NSMutableDictionary dictionary];
        [muDicParameters setObject:[NSString stringWithFormat:@"%ld",paggge] forKey:@"page"];//页码
        [muDicParameters setObject:searchBar.text forKey:@"title"];//类型
        [muDicParameters setObject:_strType forKey:@"categoryName"];
        [self startSearch];
        return YES;
    }
    
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    //NSLog(@"-----%@",searchBar.text);
    if (searchBar.text.length != 0) {
        [searchBar resignFirstResponder];
        paggge = 1;
        muDicParameters = [NSMutableDictionary dictionary];
        [muDicParameters setObject:[NSString stringWithFormat:@"%ld",paggge] forKey:@"page"];//页码
        [muDicParameters setObject:searchBar.text forKey:@"title"];//类型
        [muDicParameters setObject:_strType forKey:@"categoryName"];
        [self startSearch];
    }
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    [tableView tableViewDisplayWitMsg:@"没有查询到相对应的数据" ifNecessaryForRowCount:_aryInfo.count];
    return _aryInfo.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return 142;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dicData = _aryInfo[indexPath.row];
    
    
    
    if ([dicData[@"userType"] integerValue] == 2) {
     
    //企业
    static NSString * cellId = @"serviceCellID";
    SoftEnterpriseCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        cell = [[SoftEnterpriseCell alloc] init];
    }
    cell.titleLabel.text = dicData[@"title"];
    //设置圆形头像
    [cell.headPhoto.layer setCornerRadius:cell.headPhoto.frame.size.height/2];
    [cell.headPhoto.layer setMasksToBounds:YES];
    [cell.headPhoto setContentMode:UIViewContentModeScaleAspectFill];
    [cell.headPhoto setClipsToBounds:YES];
    cell.headPhoto.layer.shadowColor = [UIColor blackColor].CGColor;
    cell.headPhoto.layer.shadowOffset = CGSizeMake(4, 4);
    cell.headPhoto.layer.shadowOpacity = 0.5;
    cell.headPhoto.layer.shadowRadius = 2.0;
    cell.headPhoto.userInteractionEnabled = YES;
    [cell.headPhoto sd_setImageWithURL:dicData[@"headPhoto"] placeholderImage:[UIImage imageNamed:@"project_detail_taoxin_normal"]];
    
    cell.addressLabel.text = dicData[@"address"];
    
    
    //自定义的label
    UILabel *label = [[UILabel alloc] init];
    if (dicData[@"username"] == nil ||[dicData[@"username"] isEqualToString:@""]||[dicData[@"username"] isEqualToString:@"null"]) {
                label.text = dicData[@"account"];
            }else{
                label.text = dicData[@"username"];
        }
    label.numberOfLines = 1;
    label.font = [UIFont systemFontOfSize:17];
    label.textColor = cell.companyName.textColor;
    CGSize size = [label.text sizeWithFont:[UIFont systemFontOfSize:17] constrainedToSize:CGSizeMake(MAXFLOAT, 21)];
    if (size.width > screenW-140) {
        size.width = screenW-140;
    }

    CGRect frameC = cell.companyName.frame;
    frameC.size.width = size.width;
    label.frame = frameC;
    [cell addSubview:label];
    
    UIImageView *authImageView = [[UIImageView alloc] initWithFrame:CGRectMake(label.frame.origin.x+label.frame.size.width+8, label.frame.origin.y+3, 15, 15)];
    
    
//        if ([dicData[@"authState"] integerValue] == 2) {
//            //已认证
//            authImageView.image = [UIImage imageNamed:@"yirenzheng"];
//        }else{
//            
//            authImageView.image = [UIImage imageNamed:@"weirenzheng"];
//        }
        //认证
        cell.isAuthState.hidden = [UsedTool authStateImageViewHidden:dicData[@"authState"]];
        //会员图标
        authImageView.image = [UsedTool setVipimage:dicData[@"vipLevel"]];
        [cell addSubview:authImageView];
        
        return cell;
    }else{
        
        //个人
        static NSString *cellIdentifier = @"serviceCell";
        SoftwareCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (!cell) {
            cell = [[SoftwareCell alloc] init];
        }
        
        NSDictionary *dicData = _aryInfo[indexPath.row];
        cell.titleLabel.text =dicData[@"title"];
        
        
        //设置圆形头像
        [cell.headPhotoImageView.layer setCornerRadius:cell.headPhotoImageView.frame.size.height/2];
        [cell.headPhotoImageView.layer setMasksToBounds:YES];
        [cell.headPhotoImageView setContentMode:UIViewContentModeScaleAspectFill];
        [cell.headPhotoImageView setClipsToBounds:YES];
        cell.headPhotoImageView.layer.shadowColor = [UIColor blackColor].CGColor;
        cell.headPhotoImageView.layer.shadowOffset = CGSizeMake(4, 4);
        cell.headPhotoImageView.layer.shadowOpacity = 0.5;
        cell.headPhotoImageView.layer.shadowRadius = 2.0;
        cell.headPhotoImageView.userInteractionEnabled = YES;
        
        [cell.headPhotoImageView sd_setImageWithURL:dicData[@"headPhoto"] placeholderImage:[UIImage imageNamed:@"project_detail_taoxin_normal"]];
        
        if (dicData[@"username"] == nil ||[dicData[@"username"] isEqualToString:@""]||[dicData[@"username"] isEqualToString:@"null"]) {
            cell.commentUserName.text = dicData[@"account"];
        }else{
            cell.commentUserName.text = dicData[@"username"];
        }
        
        cell.posiTion.text = dicData[@"posiTionName"];
        if (dicData[@"posiTionName"]==nil||[dicData[@"posiTionName"] isEqualToString:@"null"]) {
            cell.posiTion.text = @"";
        }
        
        //    if ([dicData[@"authState"] integerValue] == 2) {
        //
        //        cell.authStateImageView.image = [UIImage imageNamed:@"yirenzheng"];
        //    }else{
        //
        //        cell.authStateImageView.image = [UIImage imageNamed:@"weirenzheng"];
        //    }
        //认证
        cell.isAuthState.hidden = [UsedTool authStateImageViewHidden:dicData[@"authState"]];
        //会员图标
        cell.authStateImageView.image = [UsedTool setVipimage:dicData[@"vipLevel"]];
        //判断上级
        cell.companyUserName.text = [UsedTool userType:dicData[@"userType"] companyName:dicData[@"companyName"] userAddress:dicData[@"userAddress"]];
        return cell;
    }
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];//取消选中状态
    
    //取消显示后退键文字
    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleDone target:nil action:nil];
    self.navigationItem.backBarButtonItem = barButtonItem;

    //推出详细界面
    serviceInfo *serviceInfoVC = [[serviceInfo alloc] initWithNibName:@"serviceInfo" bundle:nil];
    serviceInfoVC.serviceId = _aryInfo[indexPath.row][@"serviceId"];
    [self.navigationController pushViewController:serviceInfoVC animated:YES];
    
//    strProjectId = _aryInfo[indexPath.row][@"serviceId"];
//    [self performSegueWithIdentifier:@"softwareDevelop_detail" sender:self];
    
    
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // segue.identifier：获取连线的ID
    if ([segue.identifier isEqualToString:@"softwareDevelop_detail"]) {
        SoftwareDevelop_Detail *result = segue.destinationViewController;
        result.projectId = strProjectId;
    }else if ([segue.identifier isEqualToString:@"pushSoftwareDevelopShaiXuan"])
    {
        SoftwareDevelop_ShaiXuan *shaixuan = segue.destinationViewController;
        shaixuan.strType = _strType;
    }
}


- (void)startSearch
{
    NSString *strURl = [NSString stringWithFormat:@"%@%@",URL_DEFINE,@"getService_app_service.im"];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager POST:strURl parameters:muDicParameters progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];
        //NSLog(@"%@",dicInfo);

        if ([[dicInfo objectForKey:@"result"] integerValue] == 1) {
            
            if (paggge == 1) {
                [_mainTableView.mj_header endRefreshing];
                
                _aryInfo = [NSMutableArray arrayWithArray:[dicInfo objectForKey:@"data"][@"record"]];
                //NSLog(@"aryInfo:%@",_aryInfo);
                if (_aryInfo.count == 10) {
                    _mainTableView.mj_footer.hidden = NO;
                }else {
                    _mainTableView.mj_footer.hidden = YES;
                }
                
            }else {
                [_mainTableView.mj_footer endRefreshing];
                NSArray *ary11 = [dicInfo objectForKey:@"data"][@"record"];
                for (int i = 0; i<ary11.count; i++) {
                    NSDictionary *dic1 = ary11[i];
                    [_aryInfo addObject:dic1];
                }
                if (ary11.count == 10) {
                    _mainTableView.mj_footer.hidden = NO;
                }else {
                    _mainTableView.mj_footer.hidden = YES;
                }
                
            }
            
            
            [_mainTableView reloadData];
            [self hideBubble];

        }else {
            [_mainTableView reloadData];
            [_mainTableView.mj_header endRefreshing];
            [_mainTableView.mj_footer endRefreshing];

            [self showSingleIconBubble:[dicInfo objectForKey:@"msg"]];

        }
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [_mainTableView.mj_header endRefreshing];
        [_mainTableView.mj_footer endRefreshing];

        [self showSingleIconBubble:error.localizedDescription];

    }];
}

@end
